<template>
    <el-main class="main-container">
        <!-- 1. 头部 -->
        <div class="header-wrapper">
            <div class="page-title">
                <h1>商品管理</h1>
                <p>管理店铺商品信息和状态</p>
            </div>
            <div class="user-profile">
                <el-dropdown trigger="hover" @command="handleDropdownCommand">
                    <div class="avatar-wrapper">
                        <el-badge :value="lowStockCount" :max="99" :hidden="!lowStockCount">
                            <el-avatar class="user-avatar" :src="$store.state.user.headPicture"
                                @error="handleAvatarError">
                                <i class="el-icon-user-solid"></i>
                            </el-avatar>
                        </el-badge>
                        <div class="user-info">
                            <span class="user-name">{{ $store.state.user.name || '管理员' }}</span>
                            <span class="user-role">商品管理员</span>
                        </div>
                        <i class="el-icon-arrow-down dropdown-icon"></i>
                    </div>
                    <el-dropdown-menu slot="dropdown" class="custom-dropdown">
                        <el-dropdown-item command="profile" icon="el-icon-user">个人资料</el-dropdown-item>
                        <el-dropdown-item command="upload" icon="el-icon-camera">更换头像</el-dropdown-item>
                        <el-dropdown-item command="settings" icon="el-icon-setting">系统设置</el-dropdown-item>
                        <el-dropdown-item divided command="logout" icon="el-icon-switch-button">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>

        <!-- 2. 统计卡片 -->
        <div class="stats-section">
            <div class="stat-card">
                <div class="stat-icon total"><i class="el-icon-goods"></i></div>
                <div class="stat-content">
                    <div class="stat-value">{{ total }}</div>
                    <div class="stat-label">商品总数</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon active"><i class="el-icon-check"></i></div>
                <div class="stat-content">
                    <div class="stat-value">{{ onSaleCount }}</div>
                    <div class="stat-label">在售商品</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon inactive"><i class="el-icon-close"></i></div>
                <div class="stat-content">
                    <div class="stat-value">{{ offSaleCount }}</div>
                    <div class="stat-label">已下架</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon online"><i class="el-icon-warning"></i></div>
                <div class="stat-content">
                    <div class="stat-value">{{ lowStockCount }}</div>
                    <div class="stat-label">低库存</div>
                </div>
            </div>
        </div>

        <!-- 3. 搜索 & 操作栏 -->
        <div class="action-section">
            <div class="search-filters">
                <!-- 搜索类型 -->
                <el-select v-model="searchType" placeholder="搜索类型" class="search-type-select">
                    <el-option label="商品名称" value="GOODS_NAME"></el-option>
                    <el-option label="商品分类" value="GOODS_TYPE"></el-option>
                    <el-option label="商品ID" value="GOODS_ID"></el-option>
                </el-select>

                <!-- 搜索输入框 -->
                <el-input v-model="searchValue" placeholder="请输入搜索内容..." clearable class="search-input"
                    @clear="handleClear" @keyup.enter.native="handleSearch">
                    <i slot="prefix" class="el-icon-search"></i>
                </el-input>

                <!-- 状态筛选 -->
                <el-select v-model="filters.status" placeholder="商品状态" clearable class="filter-select">
                    <el-option label="全部状态" value=""></el-option>
                    <el-option label="在售" :value="1"></el-option>
                    <el-option label="下架" :value="0"></el-option>
                    <el-option label="缺货" :value="2"></el-option>
                </el-select>

                <!-- 分类筛选 -->
                <el-select v-model="filters.goodsType" placeholder="商品分类" clearable class="filter-select">
                    <el-option label="全部分类" :value="null"></el-option>
                    <el-option v-for="item in goodsTypeOptions" :key="item.id" :label="item.typeName"
                        :value="item.typeValue">
                    </el-option>
                </el-select>

                <!-- 价格区间 -->
                <div class="price-range-wrapper">
                    <span class="range-label">价格范围</span>
                    <el-input-number v-model="filters.minPrice" :min="0" :max="100000" :step="1" :precision="2"
                        size="small" placeholder="最低" class="price-input" controls-position="right" />
                    <span class="range-separator">~</span>
                    <el-input-number v-model="filters.maxPrice" :min="0" :max="100000" :step="1" :precision="2"
                        size="small" placeholder="最高" class="price-input" controls-position="right" />
                </div>

                <!-- 按钮 -->
                <el-button type="primary" icon="el-icon-search" @click="handleSearch"
                    :loading="listLoading">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
            </div>

            <div class="action-buttons">
                <el-button type="success" icon="el-icon-plus" @click="handleAdd">添加商品</el-button>
                <!-- 添加商品类型管理按钮 -->
                <el-button type="primary" icon="el-icon-folder-add" @click="handleAddGoodsType">
                    添加商品类型
                </el-button>
                <el-button type="warning" icon="el-icon-folder-delete" @click="handleDeleteGoodsType">
                    删除商品类型
                </el-button>
                <el-button type="danger" icon="el-icon-delete" :disabled="!multipleSelection.length"
                    @click="handleBatchDelete">
                    批量删除 ({{ multipleSelection.length }})
                </el-button>
                <el-button type="info" icon="el-icon-download" @click="handleExport">导出数据</el-button>
            </div>
        </div>

        <!-- 4. 表格 -->
        <div class="table-section">
            <el-table v-loading="listLoading" :data="tableData" stripe
                :header-cell-style="{ background: '#fafafa', color: '#606266' }"
                @selection-change="handleSelectionChange" @row-click="handleRowClick">

                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="id" label="商品ID" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag size="small" type="info">#{{ row.id }}</el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="商品图片" width="90" align="center">
                    <template #default="{ row }">
                        <div class="goods-image-cell">
                            <el-image :src="row.image || '/placeholder-goods.jpg'" class="goods-image" fit="cover"
                                :preview-src-list="[row.image || '/placeholder-goods.jpg']">
                                <div slot="error" class="image-slot"><i class="el-icon-picture"></i></div>
                            </el-image>
                            <div v-if="row.isSeckill" class="seckill-indicator">秒杀</div>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="goodsName" label="商品名称" min-width="180" show-overflow-tooltip>
                    <template #default="{ row }">
                        <div class="goods-name-cell">
                            <span class="goods-name">{{ row.goodsName }}</span>
                            <div class="goods-tags">
                                <el-tag v-if="row.isSeckill" size="mini" type="danger">秒杀</el-tag>
                                <el-tag v-if="row.isNew" size="mini" type="success">新品</el-tag>
                                <el-tag v-if="row.isHot" size="mini" type="warning">热销</el-tag>
                            </div>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="goodsType" label="商品分类" width="120" align="center">
                    <template #default="{ row }">
                        <el-tag size="small">{{ getGoodsTypeText(row.goodsType) }}</el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="price" label="价格" width="120" align="center">
                    <template #default="{ row }">
                        <div class="price-cell">
                            <span class="price-text">¥{{ formatPrice(row.price) }}</span>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="sale" label="销量" width="100" align="center" sortable>
                    <template #default="{ row }">
                        <span class="sale-count">{{ row.sale || 0 }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="stock" label="库存" width="100" align="center">
                    <template #default="{ row }">
                        <span :class="['stock-count', { 'low-stock': (row.stock || 0) < 10 }]">
                            {{ row.stock || 0 }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column prop="status" label="状态" width="100" align="center">
                    <template #default="{ row }">
                        <el-switch v-model="row.status" :active-value="1" :inactive-value="0" active-color="#13ce66"
                            inactive-color="#ff4949" @click.native.stop
                            @change="handleStatusChange(row.id, row.status)" />
                    </template>
                </el-table-column>

                <el-table-column prop="createTime" label="创建时间" width="160" align="center">
                    <template #default="{ row }"><span>{{ formatDate(row.createTime) }}</span></template>
                </el-table-column>

                <el-table-column label="操作" width="220" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-tooltip content="查看详情" placement="top">
                            <el-button size="mini" type="info" icon="el-icon-view" circle
                                @click.stop="handleView(row)" />
                        </el-tooltip>
                        <el-tooltip content="编辑" placement="top">
                            <el-button size="mini" type="primary" icon="el-icon-edit" circle
                                @click.stop="handleEdit(row)" />
                        </el-tooltip>
                        <el-tooltip content="库存管理" placement="top">
                            <el-button size="mini" type="warning" icon="el-icon-tickets" circle
                                @click.stop="handleStock(row)" />
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button size="mini" type="danger" icon="el-icon-delete" circle
                                @click.stop="handleDelete(row)" />
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 5. 分页 -->
        <div class="pagination-section">
            <div class="pagination-info">共 {{ total }} 条，每页 {{ pageSize }} 条</div>
            <el-pagination background :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]"
                :page-size.sync="pageSize" :total="total" layout="sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handlePageChange">
            </el-pagination>
        </div>

        <!-- 6. 添加/编辑弹窗 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" :before-close="handleDialogClose"
            :close-on-click-modal="false" custom-class="goods-dialog">
            <el-form :model="goodsForm" :rules="formRules" ref="goodsFormRef" label-width="100px" class="goods-form">
                <div class="form-section">
                    <h3 class="section-title">基本信息</h3>
                    <el-form-item label="商品名称" prop="goodsName">
                        <el-input v-model="goodsForm.goodsName" placeholder="请输入商品名称" clearable></el-input>
                    </el-form-item>

                    <el-form-item label="商品分类" prop="goodsType">
                        <el-select v-model="goodsForm.goodsType" placeholder="请选择分类" style="width:100%">
                            <el-option v-for="item in goodsTypeOptions" :key="item.id" :label="item.typeName"
                                :value="item.goodsType">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="商品价格" prop="price">
                                <el-input-number v-model="goodsForm.price" :min="0" :max="100000" :step="0.01"
                                    :precision="2" placeholder="请输入价格" style="width:100%">
                                    <template slot="prepend">¥</template>
                                </el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="商品库存" prop="stock">
                                <el-input-number v-model="goodsForm.stock" :min="0" :max="100000" :step="1"
                                    placeholder="请输入库存" style="width:100%">
                                </el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="商品描述">
                        <el-input type="textarea" v-model="goodsForm.description" :rows="4"
                            placeholder="请输入商品描述（选填）"></el-input>
                    </el-form-item>
                </div>

                <div class="form-section">
                    <h3 class="section-title">商品图片</h3>
                    <el-form-item label="商品图片" prop="image">
                        <el-upload class="goods-uploader" action="#" :show-file-list="false"
                            :before-upload="handleBeforeUpload" :http-request="handleUploadImage" accept="image/*">
                            <img v-if="goodsForm.image" :src="goodsForm.image" class="goods-image-preview">
                            <div v-else class="upload-placeholder">
                                <i class="el-icon-plus upload-icon"></i>
                                <div class="upload-text">点击上传图片</div>
                                <div class="upload-tip">支持 JPG、PNG，最大 2MB</div>
                            </div>
                        </el-upload>
                    </el-form-item>
                </div>

                <div class="form-section">
                    <h3 class="section-title">商品设置</h3>
                    <el-form-item label="秒杀商品">
                        <el-switch v-model="goodsForm.isSeckill" active-color="#f56c6c"></el-switch>
                        <span class="setting-desc">标记为秒杀商品</span>
                    </el-form-item>
                    <el-form-item label="新品标识">
                        <el-switch v-model="goodsForm.isNew" active-color="#67c23a"></el-switch>
                        <span class="setting-desc">显示"新品"标签</span>
                    </el-form-item>
                    <el-form-item label="热销商品">
                        <el-switch v-model="goodsForm.isHot" active-color="#e6a23c"></el-switch>
                        <span class="setting-desc">显示"热销"标签</span>
                    </el-form-item>
                    <el-form-item label="上架状态">
                        <el-switch v-model="goodsForm.status" :active-value="1" :inactive-value="0"
                            active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                        <span class="setting-desc">{{ goodsForm.status === 1 ? '在售' : '下架' }}</span>
                    </el-form-item>
                </div>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="handleDialogClose">取 消</el-button>
                <el-button type="primary" @click="handleSubmitForm" :loading="submitLoading">
                    {{ isEdit ? '保存修改' : '立即创建' }}
                </el-button>
            </span>
        </el-dialog>

        <!-- 7. 详情弹窗 -->
        <el-dialog title="商品详情" :visible.sync="detailDialogVisible" width="700px"
            :before-close="() => detailDialogVisible = false">
            <div v-if="currentGoods" class="goods-detail">
                <div class="detail-header">
                    <div class="detail-image">
                        <el-image :src="currentGoods.image || '/placeholder-goods.jpg'" class="detail-goods-image"
                            fit="cover">
                            <div slot="error" class="image-slot"><i class="el-icon-picture"></i></div>
                        </el-image>
                        <div v-if="currentGoods.isSeckill" class="seckill-badge">秒杀</div>
                    </div>
                    <div class="detail-info">
                        <h3>{{ currentGoods.goodsName }}</h3>
                        <p class="goods-type">{{ getGoodsTypeText(currentGoods.goodsType) }}</p>
                        <div class="goods-status-tags">
                            <el-tag :type="getStatusType(currentGoods.status)">
                                {{ getStatusText(currentGoods.status) }}
                            </el-tag>
                            <el-tag v-if="currentGoods.isSeckill" type="danger">秒杀商品</el-tag>
                            <el-tag v-if="currentGoods.isNew" type="success">新品</el-tag>
                            <el-tag v-if="currentGoods.isHot" type="warning">热销</el-tag>
                        </div>
                        <div class="price-display">
                            <span class="price">¥{{ formatPrice(currentGoods.price) }}</span>
                            <span class="stock">库存: {{ currentGoods.stock || 0 }}</span>
                        </div>
                    </div>
                </div>
                <el-divider></el-divider>
                <div class="detail-content">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <p><strong>商品ID：</strong>#{{ currentGoods.id }}</p>
                            <p><strong>商品分类：</strong>{{ getGoodsTypeText(currentGoods.goodsType) }}</p>
                            <p><strong>创建时间：</strong>{{ formatDate(currentGoods.createTime) }}</p>
                        </el-col>
                        <el-col :span="12">
                            <p><strong>销量：</strong>{{ currentGoods.sale || 0 }}</p>
                            <p><strong>库存：</strong>{{ currentGoods.stock || 0 }}</p>
                            <p><strong>月销售额：</strong>¥{{ formatPrice((currentGoods.sale || 0) * (currentGoods.price ||
                                0)) }}
                            </p>
                        </el-col>
                    </el-row>
                    <div v-if="currentGoods.description" class="goods-description">
                        <p><strong>商品描述：</strong></p>
                        <p>{{ currentGoods.description }}</p>
                    </div>
                </div>
            </div>
            <span slot="footer">
                <el-button @click="detailDialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="handleEdit(currentGoods)">编辑商品</el-button>
                <el-button type="warning" @click="handleStock(currentGoods)">库存管理</el-button>
            </span>
        </el-dialog>

        <!-- 8. 添加商品类型弹窗 -->
        <el-dialog title="添加商品类型" :visible.sync="goodsTypeDialogVisible" width="500px">
            <el-form :model="goodsTypeForm" :rules="goodsTypeRules" ref="goodsTypeFormRef" label-width="100px">
                <el-form-item label="类型名称" prop="typeName">
                    <el-input v-model="goodsTypeForm.typeName" placeholder="请输入商品类型名称" clearable></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="goodsTypeDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmitGoodsType" :loading="goodsTypeLoading">
                    确认添加
                </el-button>
            </span>
        </el-dialog>

        <!-- 9. 删除商品类型弹窗 -->
        <el-dialog title="删除商品类型" :visible.sync="deleteGoodsTypeDialogVisible" width="500px">
            <div class="delete-goods-type-dialog">
                <p>请选择要删除的商品类型：</p>
                <el-select v-model="selectedGoodsType" placeholder="选择商品类型" style="width: 100%" clearable>
                    <el-option v-for="item in goodsTypeOptions" :key="item.id" :label="item.typeName"
                        :value="item.goodsType">
                        <!-- 使用 goodsType -->
                    </el-option>
                </el-select>
                <p class="delete-warning">注意：删除商品类型可能会影响已关联该类型的商品！</p>
            </div>
            <span slot="footer">
                <el-button @click="deleteGoodsTypeDialogVisible = false">取消</el-button>
                <el-button type="danger" @click="handleConfirmDeleteGoodsType" :loading="deleteGoodsTypeLoading"
                    :disabled="!selectedGoodsType">
                    确认删除
                </el-button>
            </span>
        </el-dialog>
    </el-main>
</template>

<script>
import {
    batchDelete, updateGoods, getGoodsType,
    updateGoodsStatus, getGoodsList, addGoods,
    getGoodsByImportanceKey, AddStoreType, deleteStoreType
} from '@/api/admin/Goods'
import { getStoreId } from '@/api/admin/store';
import { upload } from '@/api/common/common'

export default {
    name: 'GoodsManagement',
    data() {
        return {
            filters: {
                status: '',
                goodsType: null,
                minPrice: null,
                maxPrice: null
            },
            searchType: 'GOODS_NAME',
            searchValue: '',
            currentPage: 1,
            pageSize: 10,
            total: 0,
            listLoading: false,
            tableData: [],
            multipleSelection: [],
            detailDialogVisible: false,
            currentGoods: null,
            lowStockCount: 0,
            isSearching: false,

            // 商品类型管理相关
            goodsTypeDialogVisible: false,
            deleteGoodsTypeDialogVisible: false,
            goodsTypeLoading: false,
            deleteGoodsTypeLoading: false,
            selectedGoodsType: null,
            goodsTypeForm: {
                typeName: ''
            },
            goodsTypeRules: {
                typeName: [
                    { required: true, message: '请输入商品类型名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '类型名称长度在 1 到 20 个字符', trigger: 'blur' }
                ]
            },

            dialogVisible: false,
            isEdit: false,
            submitLoading: false,
            goodsForm: {
                id: null,
                goodsName: '',
                goodsType: '',
                price: 0,
                stock: 0,
                description: '',
                image: '',
                isSeckill: false,
                isNew: false,
                isHot: false,
                status: 1
            },
            goodsTypeOptions: [],
            formRules: {
                goodsName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                goodsType: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
                price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
                stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }]
            }
        }
    },
    computed: {
        dialogTitle() { return this.isEdit ? '编辑商品' : '添加新商品' },
        onSaleCount() { return this.tableData.filter(i => i.status === 1).length },
        offSaleCount() { return this.tableData.filter(i => i.status === 0).length }
    },
    methods: {
        // 商品类型管理方法
        handleAddGoodsType() {
            this.goodsTypeForm.typeName = ''
            this.goodsTypeDialogVisible = true
            this.$nextTick(() => {
                this.$refs.goodsTypeFormRef?.clearValidate()
            })
        },

        handleDeleteGoodsType() {
            if (this.goodsTypeOptions.length === 0) {
                this.$message.warning('暂无商品类型可删除')
                return
            }
            this.selectedGoodsType = null
            this.deleteGoodsTypeDialogVisible = true
        },

        async handleSubmitGoodsType() {
            this.$refs.goodsTypeFormRef.validate(async (valid) => {
                if (!valid) return

                try {
                    this.goodsTypeLoading = true
                    const res = await AddStoreType(this.goodsTypeForm.typeName)

                    if (res.data.code === 1) {
                        this.$message.success('商品类型添加成功')
                        this.goodsTypeDialogVisible = false
                        // 重新加载商品类型
                        await this.loadGoodsTypes()
                    } else {
                        throw new Error(res.data.msg || '添加失败')
                    }
                } catch (error) {
                    console.error('添加商品类型失败:', error)
                    this.$message.error(error.message || '添加商品类型失败')
                } finally {
                    this.goodsTypeLoading = false
                }
            })
        },

        async handleConfirmDeleteGoodsType() {
            if (!this.selectedGoodsType) {
                this.$message.warning('请选择要删除的商品类型')
                return
            }

            try {
                this.deleteGoodsTypeLoading = true
                // 根据 goodsType 查找对应的商品类型对象
                const selectedType = this.goodsTypeOptions.find(item => item.goodsType === this.selectedGoodsType)

                await this.$confirm(
                    `确定删除商品类型 "${this.selectedGoodsType}" 吗？此操作不可恢复！`,
                    '删除确认',
                    {
                        type: 'warning',
                        confirmButtonText: '确定删除',
                        cancelButtonText: '取消'
                    }
                )
                console.log('要删除的商品类型:', this.selectedGoodsType);

                // 调用删除接口，传递 goodsType
                const res = await deleteStoreType(this.selectedGoodsType)

                if (res.data.code === 1) {
                    this.$message.success('商品类型删除成功')
                    this.deleteGoodsTypeDialogVisible = false
                    this.selectedGoodsType = null
                    // 重新加载商品类型
                    await this.loadGoodsTypes()
                } else {
                    throw new Error(res.data.msg || '删除失败')
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除商品类型失败:', error)
                    this.$message.error(error.message || '删除商品类型失败')
                }
            } finally {
                this.deleteGoodsTypeLoading = false
            }
        },

        // 原有方法保持不变
        handleClear() {
            this.searchValue = ''
            this.isSearching = false
            this.currentPage = 1
            this.loadData()
        },

        formatPrice(price) {
            return Number(price || 0).toFixed(2)
        },

        formatDate(date) {
            return date ? new Date(date).toLocaleString('zh-CN') : '-'
        },

        getStatusText(status) {
            const statusMap = { 0: '下架', 1: '在售', 2: '缺货' }
            return statusMap[status] || '未知'
        },

        getStatusType(status) {
            const typeMap = { 0: 'danger', 1: 'success', 2: 'warning' }
            return typeMap[status] || 'info'
        },

        getGoodsTypeText(typeValue) {
            const found = this.goodsTypeOptions.find(t => t.typeValue === typeValue)
            return found ? found.typeName : '未知分类'
        },

        handleSelectionChange(val) {
            this.multipleSelection = val
        },

        handleRowClick(row, column, event) {
            const isCheckbox = event.target.classList.contains('el-checkbox__inner')
            const isButton = event.target.tagName === 'BUTTON'
            if (!isCheckbox && !isButton && column.property !== 'selection') {
                this.handleView(row)
            }
        },

        async handlePageChange(p) {
            this.currentPage = p
            if (this.isSearching) {
                await this.handleSearch()
            } else {
                await this.loadData()
            }
        },

        async handleSizeChange(s) {
            this.pageSize = s
            this.currentPage = 1
            if (this.isSearching) {
                await this.handleSearch()
            } else {
                await this.loadData()
            }
        },

        async handleSearch() {
            console.log('🔍 搜索类型:', this.searchType)
            console.log('🔍 搜索内容:', this.searchValue)
            console.log('🔍 筛选条件:', this.filters)

            this.listLoading = true

            try {
                if (!this.searchValue.trim()) {
                    this.isSearching = false
                    this.currentPage = 1
                    await this.loadData()
                    return
                }

                this.isSearching = true

                const params = {
                    imformationWord: this.searchValue.trim(),
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    searchType: this.searchType,
                    sellerID: getStoreId()
                }

                if (this.filters.status !== '') {
                    params.status = this.filters.status
                }
                if (this.filters.goodsType !== null) {
                    params.goodsType = this.filters.goodsType
                }
                if (this.filters.minPrice !== null) {
                    params.minPrice = this.filters.minPrice
                }
                if (this.filters.maxPrice !== null) {
                    params.maxPrice = this.filters.maxPrice
                }

                console.log('📤 搜索参数:', params)

                const res = await getGoodsByImportanceKey(params)

                console.log('📥 搜索响应:', res)

                if (res && res.data) {
                    if (res.data.code === 1 && res.data.data) {
                        this.tableData = res.data.data.records || []
                        this.total = res.data.data.total || 0
                    } else if (res.data.records) {
                        this.tableData = res.data.records || []
                        this.total = res.data.total || 0
                    } else {
                        this.tableData = []
                        this.total = 0
                    }

                    if (this.tableData.length === 0) {
                        this.$message.info('未找到相关商品')
                    } else {
                        this.$message.success(`找到 ${this.total} 个商品`)
                    }
                } else {
                    this.tableData = []
                    this.total = 0
                    this.$message.warning('搜索结果为空')
                }

            } catch (error) {
                console.error("❌ 搜索失败:", error)
                this.$message.error(error.message || '搜索失败，请稍后重试')
                this.tableData = []
                this.total = 0
            } finally {
                this.listLoading = false
            }
        },

        async handleRefresh() {
            this.filters = { status: '', goodsType: null, minPrice: null, maxPrice: null }
            this.searchValue = ''
            this.searchType = 'GOODS_NAME'
            this.isSearching = false
            this.currentPage = 1
            await this.loadData()
            this.$message.success('已重置')
        },

        handleAdd() {
            this.isEdit = false
            this.resetForm()
            this.dialogVisible = true
        },

        handleEdit(row) {
            this.isEdit = true
            this.goodsForm = {
                ...row,
                image: row.image || ''
            }
            this.dialogVisible = true
        },

        handleView(row) {
            this.currentGoods = row
            this.detailDialogVisible = true
        },

        handleStock(row) {
            this.$message.info(`进入 ${row.goodsName} 的库存管理`)
            // 这里可以跳转到库存管理页面
        },

        handleDialogClose() {
            this.$confirm('确认关闭？', '提示', { type: 'warning' })
                .then(() => {
                    this.dialogVisible = false
                    this.resetForm()
                })
                .catch(() => { })
        },

        resetForm() {
            this.goodsForm = {
                id: null,
                goodsName: '',
                goodsType: '',
                price: 0,
                stock: 0,
                description: '',
                image: '',
                isSeckill: false,
                isNew: false,
                isHot: false,
                status: 1
            }
            this.$nextTick(() => this.$refs.goodsFormRef?.clearValidate())
        },

        handleBeforeUpload(file) {
            const isImg = file.type.startsWith('image/')
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!isImg) {
                this.$message.error('只能上传图片格式')
                return false
            }
            if (!isLt2M) {
                this.$message.error('图片大小不能超过 2MB')
                return false
            }
            return true
        },

        async handleUploadImage(param) {
            try {
                const fd = new FormData()
                fd.append('file', param.file)
                const res = await upload(fd)
                this.goodsForm.image = res
                this.$message.success('上传成功')
            } catch (error) {
                console.error('上传失败:', error)
                this.$message.error('上传失败')
            }
        },

        handleSubmitForm() {
            this.$refs.goodsFormRef.validate(async valid => {
                if (!valid) {
                    this.$message.warning('请填写完整信息')
                    return
                }

                try {
                    this.submitLoading = true
                    this.goodsForm.isSeckill = this.goodsForm.isSeckill == true ? 1 : 0;
                    const postData = {
                        ...this.goodsForm,
                        sellerID: getStoreId()
                    }

                    console.log('📤 提交数据:', postData)

                    if (this.isEdit) {
                        await updateGoods(postData)
                        this.$message.success('更新成功')
                    } else {
                        const res = await addGoods(postData)
                        if (res.data.code === 1) {
                            this.$message.success('添加成功')
                        } else {
                            throw new Error(res.data.msg || '添加失败')
                        }
                    }

                    this.dialogVisible = false
                    this.resetForm()
                    await this.loadData()

                } catch (err) {
                    console.error('❌ 提交错误:', err)
                    this.$message.error(err.message || (this.isEdit ? '更新失败' : '添加失败'))
                } finally {
                    this.submitLoading = false
                }
            })
        },

        async handleBatchDelete() {
            if (!this.multipleSelection.length) {
                this.$message.warning('请选择要删除的商品')
                return
            }

            try {
                await this.$confirm(`确定删除 ${this.multipleSelection.length} 个商品？`, '警告', {
                    type: 'warning',
                    confirmButtonText: '确定删除',
                    cancelButtonText: '取消'
                })

                const ids = this.multipleSelection.map(i => i.id)
                await batchDelete(ids)
                this.$message.success('删除成功')
                this.multipleSelection = []

                if (this.tableData.length === ids.length && this.currentPage > 1) {
                    this.currentPage--
                }

                await this.loadData()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除失败:', error)
                    this.$message.error('删除失败')
                }
            }
        },

        async handleDelete(row) {
            try {
                await this.$confirm('确定删除该商品？', '警告', {
                    type: 'warning',
                    confirmButtonText: '确定删除',
                    cancelButtonText: '取消'
                })

                await batchDelete([row.id])
                this.$message.success('删除成功')

                if (this.tableData.length === 1 && this.currentPage > 1) {
                    this.currentPage--
                }

                await this.loadData()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除失败:', error)
                    this.$message.error('删除失败')
                }
            }
        },

        async handleStatusChange(id, status) {
            try {
                const res = await updateGoodsStatus(id, status)
                if (res.data.code === 1) {
                    this.$message.success('状态更新成功')
                } else {
                    throw new Error('更新失败')
                }
            } catch (error) {
                const item = this.tableData.find(i => i.id === id)
                if (item) {
                    item.status = status === 1 ? 0 : 1
                }
                console.error('状态更新失败:', error)
                this.$message.error('状态更新失败')
            }
        },

        handleExport() {
            this.$message.info('导出功能开发中...')
        },

        handleDropdownCommand(cmd) {
            const actions = {
                profile: () => this.$message.info('个人资料功能开发中...'),
                upload: () => this.$message.info('更换头像功能开发中...'),
                settings: () => this.$message.info('系统设置功能开发中...'),
                logout: () => this.handleLogout()
            }
            actions[cmd]?.()
        },

        async handleLogout() {
            try {
                await this.$confirm('确定退出登录？', '提示', { type: 'warning' })
                this.$store.dispatch('user/logout')
                this.$router.push('/')
            } catch (error) {
                // 取消退出
            }
        },

        handleAvatarError() {
            this.$store.commit('user/UPDATE_AVATAR', '/default-avatar.png')
        },

        async loadData() {
            this.listLoading = true

            try {
                console.log('📥 加载数据，当前页:', this.currentPage, '每页:', this.pageSize)

                const res = await getGoodsList()

                console.log('📥 接口返回:', res)

                if (res && res.data) {
                    if (res.data.code === 1 && res.data.data) {
                        this.tableData = res.data.data.records || []
                        this.total = res.data.data.total || 0
                    } else if (res.data.records) {
                        this.tableData = res.data.records || []
                        this.total = res.data.total || 0
                    } else {
                        this.tableData = Array.isArray(res.data) ? res.data : []
                        this.total = this.tableData.length
                    }

                    // 计算低库存数量
                    this.lowStockCount = this.tableData.filter(item => (item.stock || 0) < 10).length

                    console.log('✅ 加载成功，数据量:', this.tableData.length)
                } else {
                    console.warn('⚠️ 返回数据格式异常:', res)
                    this.tableData = []
                    this.total = 0
                    this.lowStockCount = 0
                }
            } catch (err) {
                console.error('❌ 加载失败:', err)
                this.$message.error('加载数据失败: ' + (err.message || '未知错误'))
                this.tableData = []
                this.total = 0
                this.lowStockCount = 0
            } finally {
                this.listLoading = false
            }
        },

        async loadGoodsTypes() {
            try {
                console.log('📥 加载商品分类...')
                const res = await getGoodsType()
                console.log('📥 分类数据:', res)

                if (res && res.data) {
                    if (res.data.code === 1 && res.data.data) {
                        this.goodsTypeOptions = res.data.data || []
                    } else if (Array.isArray(res.data)) {
                        this.goodsTypeOptions = res.data || []
                    } else {
                        this.goodsTypeOptions = []
                    }

                    console.log('✅ 分类加载成功:', this.goodsTypeOptions)

                    if (this.goodsTypeOptions.length > 0 && !this.goodsForm.goodsType) {
                        this.goodsForm.goodsType = this.goodsTypeOptions[0].typeValue
                    }
                } else {
                    this.goodsTypeOptions = []
                }
            } catch (err) {
                console.error('❌ 加载商品分类失败:', err)
                this.$message.error('加载商品分类失败')
                this.goodsTypeOptions = []
            }
        }
    },

    async mounted() {
        console.log('🚀 商品管理组件挂载，开始初始化...')

        await this.loadData()
        await this.loadGoodsTypes()

        console.log('✅ 商品管理初始化完成')
    }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.main-container {
    padding: 24px;
    background: #f5f7fa;
    min-height: 100vh;
}

.header-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.page-title h1 {
    margin: 0;
    font-size: 24px;
    color: #303133;
}

.page-title p {
    margin: 8px 0 0;
    color: #909399;
    font-size: 14px;
}

.user-profile .avatar-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 8px;
    transition: all 0.3s;
}

.user-profile .avatar-wrapper:hover {
    background: #f5f7fa;
}

.user-info {
    display: flex;
    flex-direction: column;
}

.user-name {
    font-weight: 500;
    color: #303133;
}

.user-role {
    font-size: 12px;
    color: #909399;
}

.stats-section {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 24px;
}

.stat-card {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
    width: 56px;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    font-size: 24px;
    color: white;
}

.stat-icon.total {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.inactive {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.online {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
}

.stat-label {
    margin-top: 4px;
    color: #909399;
    font-size: 14px;
}

.action-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    flex-wrap: wrap;
    gap: 12px;
}

.search-filters {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    flex: 1;
    align-items: center;
}

.search-type-select {
    width: 120px;
}

.search-input {
    width: 240px;
}

.filter-select {
    width: 140px;
}

.price-range-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 0 12px;
    background: #f5f7fa;
    border-radius: 4px;
}

.range-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
}

.price-input {
    width: 100px;
}

.range-separator {
    color: #909399;
}

.action-buttons {
    display: flex;
    gap: 12px;
}

.table-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-bottom: 20px;
}

.goods-image-cell {
    position: relative;
    display: inline-block;
}

.goods-image {
    width: 60px;
    height: 60px;
    border-radius: 8px;
}

.seckill-indicator {
    position: absolute;
    top: 2px;
    right: 2px;
    background: #f56c6c;
    color: white;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 10px;
    font-weight: bold;
}

.goods-name-cell {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.goods-name {
    font-weight: 500;
    color: #303133;
}

.goods-tags {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
}

.price-cell {
    display: flex;
    align-items: center;
    justify-content: center;
}

.price-text {
    font-weight: 600;
    color: #f56c6c;
    font-size: 16px;
}

.sale-count {
    font-weight: 500;
    color: #606266;
}

.stock-count {
    font-weight: 500;
    color: #67c23a;
}

.stock-count.low-stock {
    color: #e6a23c;
    font-weight: 600;
}

.pagination-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

.goods-form .form-section {
    margin-bottom: 24px;
}

.section-title {
    margin: 0 0 16px;
    padding-bottom: 12px;
    border-bottom: 2px solid #f0f0f0;
    font-size: 16px;
    color: #303133;
}

.goods-uploader {
    width: 100%;
}

.goods-image-preview {
    width: 100%;
    max-height: 300px;
    object-fit: cover;
    border-radius: 8px;
    cursor: pointer;
}

.upload-placeholder {
    width: 100%;
    height: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2px dashed #dcdfe6;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
}

.upload-placeholder:hover {
    border-color: #409eff;
    background: #f5f7fa;
}

.upload-icon {
    font-size: 48px;
    color: #c0c4cc;
}

.upload-text {
    margin-top: 12px;
    font-size: 14px;
    color: #606266;
}

.upload-tip {
    margin-top: 4px;
    font-size: 12px;
    color: #909399;
}

.setting-desc {
    margin-left: 12px;
    font-size: 13px;
    color: #909399;
}

.goods-detail {
    padding: 0;
}

.detail-header {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;
}

.detail-image {
    position: relative;
    flex-shrink: 0;
}

.detail-goods-image {
    width: 200px;
    height: 200px;
    border-radius: 12px;
}

.seckill-badge {
    position: absolute;
    top: 12px;
    right: 12px;
    padding: 6px 12px;
    background: rgba(245, 108, 108, 0.9);
    color: white;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
}

.detail-info {
    flex: 1;
}

.detail-info h3 {
    margin: 0 0 8px;
    font-size: 24px;
    color: #303133;
}

.goods-type {
    margin: 0 0 12px;
    color: #909399;
    font-size: 14px;
}

.goods-status-tags {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}

.price-display {
    display: flex;
    align-items: center;
    gap: 20px;
}

.price-display .price {
    font-size: 24px;
    font-weight: bold;
    color: #f56c6c;
}

.price-display .stock {
    font-size: 16px;
    color: #606266;
}

.detail-content p {
    margin: 8px 0;
    line-height: 1.8;
    color: #606266;
}

.goods-description {
    margin-top: 20px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 8px;
}

.goods-description p:first-child {
    margin-top: 0;
    font-weight: 500;
}

.image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 32px;
}

/* 删除商品类型弹窗样式 */
.delete-goods-type-dialog {
    padding: 10px 0;
}

.delete-warning {
    margin-top: 16px;
    padding: 12px;
    background: #fef0f0;
    border: 1px solid #fbc4c4;
    border-radius: 4px;
    color: #f56c6c;
    font-size: 14px;
}

@media (max-width: 1200px) {
    .stats-section {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .stats-section {
        grid-template-columns: 1fr;
    }

    .action-section {
        flex-direction: column;
        align-items: stretch;
    }

    .search-filters {
        flex-direction: column;
    }

    .search-type-select,
    .search-input,
    .filter-select {
        width: 100%;
    }
}
</style>